<template>
  <div class="container">
    <van-tabs v-model:active="active" @click-tab="onClickTab">
      <van-tab title="北江闸坝"></van-tab>
      <van-tab title="连江闸坝"></van-tab>      
    </van-tabs>
    <div class="content" v-show="active === 0" style="margin-top: 20px;">
      <div class="title">{{ new Date().format('yyyy年MM月dd日hh时') }}实时水位统计分析</div>
      <div id="lineChart" style="height: 300px;"></div>
    </div>
    <div class="filter" v-show="active === 0">
      <van-field
        v-model="year"
        is-link
        arrow-direction="down"
        readonly
        label=""
        placeholder="请选择"
        @click="showYearPicker = true"
      />
      <van-popup v-model:show="showYearPicker" round position="bottom">
        <van-date-picker
          v-model="currentDate"
          title="请选择"
          :min-date="new Date(2021, 0, 1)"
          :max-date="new Date()"
          :columns-type="columnsType"
          @cancel="showYearPicker = false"
          @confirm="confirmYear"
        />
      </van-popup>
    </div>
    <div class="content" v-show="active === 0">
      <div class="title">北江船闸过闸船舶货物吨位统计分析</div>
      <div class="count">
        <div class="item">
          <span class="name">总上行船舶数</span>
          <span class="value">{{ totalUpShipNum }}艘</span>
        </div>
        <div class="item">
          <span class="name">总下行船舶数</span>
          <span class="value">{{ totalDownShipNum }}艘</span>
        </div>
      </div>
      <div id="stackedChart" style="height: 200px;"></div>
    </div>
    <div class="filter" v-show="active === 0">
      <!-- <van-field
        v-model="shipLock"
        is-link
        arrow-direction="down"
        readonly
        label=""
        placeholder="请选择"
        @click="showPicker = true"
        style="width: 40%;margin-right: 5px;"
      />
      <van-popup v-model:show="showPicker" round position="bottom">
        <van-picker
          title="请选择船闸"
          :columns="shipLockOptions"
          :columns-field-names="customFieldName"
          @cancel="showPicker = false"
          @confirm="confirmShipLock"
        />
      </van-popup> -->
      <van-field
        v-model="date"
        is-link
        arrow-direction="down"
        readonly
        label=""
        placeholder="请选择日期"
        @click="showCalendar = true"
        style="width: 100%;"
      />
      <van-calendar 
        v-model:show="showCalendar" 
        type="range" 
        @confirm="confirmDate" 
        allow-same-day
        :min-date="new Date(2021, 3, 6)" 
        :max-date="new Date()"
      />
    </div>        
    <div class="content" v-show="active === 0">
      <div class="title">北江船闸过闸船舶货物类型统计分析</div>
      <div id="pieChart" style="height: 200px;"></div>
      <div class="pie-table">
        <div class="pie-tbody">
          <div class="pie-tr" v-for="(item,index) in pieChartData" :key="index">
            <div style="display: flex;align-items: center;width: 40%;">
              <div class="li" :style="`background:${item.itemStyle?item.itemStyle.color:''}`"></div>
              <div class="pie-td">{{ item.name }}</div>
            </div>     
            <div class="pie-td" style="width: 30%;">{{ item.load }}吨</div>  
            <div class="pie-td" style="width: 30%;">{{ item.value }}%</div>
          </div>
        </div>
      </div>
    </div>
    <div class="content" v-show="active === 1" style="margin-top: 16px;">
      <div class="title">变形监测统计分析</div>
      <div class="list">
        <div v-for="(item,index) in deformationData" :key="index" class="list-item">
          <div class="item-title">{{ item.name }}</div>
          <div class="item-name">
            <div>预警数</div>
            <div>一级</div>
            <div>二级</div>
            <div>三级</div>
          </div>
          <div class="item-value">
            <div>{{ item.totalnum }}</div>
            <div>{{ item.onelevel }}</div>
            <div>{{ item.twolevel }}</div>
            <div>{{ item.threelevel }}</div>
          </div>
        </div>
      </div>      
    </div>
    <div class="content" v-show="active === 1" style="padding-bottom: 16px;">
      <div class="title">变形监测观测周期统计分析</div>
      <div class="explain"><span style="color: #165DFF;">说明：</span>黄牛、黄燕、青莲、青霜水坝观测周期从2023年7月起观测周期从2月一次调整为8小时一次</div>
        <van-tabs v-model:active="active1" @click-tab="onClickTab1" ref="tabs">
          <van-tab title="船闸">
            <div id="barChart1" style="height: 300px;"></div> 
          </van-tab>
          <van-tab title="水坝">
            <div id="barChart2" style="height: 300px;"></div> 
          </van-tab>      
        </van-tabs>            
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, nextTick } from 'vue';

  import * as echarts from 'echarts/core';
  import { TooltipComponent, LegendComponent, GridComponent, DataZoomComponent } from 'echarts/components';
  import { PieChart, BarChart, LineChart } from 'echarts/charts';
  import { CanvasRenderer } from 'echarts/renderers';
  echarts.use([TooltipComponent, LegendComponent, GridComponent, DataZoomComponent, PieChart, BarChart, LineChart, CanvasRenderer]);

  // 引入api
  import {
    getShipLock, //获取船闸列表
    goodsAnalysis, //过闸船舶货物类型统计分析
    goodsTonAlys, //过闸船舶货物吨位统计分析
    defAlySmall, //变形监测统计分析
    circleAlys, //变形监测观测周期统计分析
    newWater, //实时水位统计分析
  } from "@/bridge-h5/utils/myapi";

  //标签
  const active = ref(0);
  const onClickTab = ({ title }) => {
    // getShipLockFunction();
    if(title == "北江闸坝"){
      initPieChart();
      initStackedChart();
      newWaterFunctin();
    }else if(title == "连江闸坝"){
      deformationAlysFunction();
      circleAlysFunction();
      tabs.value.resize();
    }
  };

  //获取船闸
  const shipLock = ref('');
  const shipLockOptions = ref([]);
  const customFieldName = {
    text: 'name',
    value: 'name',
  };
  const getShipLockFunction = () => {
    getShipLock(
      active.value === 0? "北江" : "连江"
    ).then((res) => {
      if(res.code === 200 && res.data.length){
        shipLockOptions.value = res.data;
        shipLock.value = res.data[1].name;
        // res.data.unshift({
        //   name: "全部"
        // });        
        // shipLock.value = "全部";

        initPieChart();
        initStackedChart();
      }
    });
  };
  const showPicker = ref(false);
  const confirmShipLock = ({ selectedOptions }) => {
    showPicker.value = false;
    shipLock.value = selectedOptions[0].name === "全部"? "" : selectedOptions[0].name;

    initPieChart();
    initStackedChart();
  };

  //日期
  const date = ref('');
  const showCalendar = ref(false);
  const confirmDate = (values) => {
    const [start, end] = values;
    date.value = new Date(start).format('yyyy-MM-dd') + '~' + new Date(end).format('yyyy-MM-dd');
    initPieChart();
    // initStackedChart();
    showCalendar.value = false;
  };

  //过闸船舶货物类型统计分析
  const pieChartData = ref([]);
  const initPieChart = () => {
    let start = date.value.split('~')[0];
    let end = date.value.split('~')[1];
    goodsAnalysis("", start, end).then((res) => {
      if(res.code === 200){  
        let seriesData = [];    
        let colorData = [
          '#6B9BFD','#af71db','#ffa257','#135ddf','#0e8a89','#ffcb32','#4ed9a0','#67cdf7','#67c577','#13cdff',
          '#91cc75','#99cdff','#10757C','#C8778E','#D4B6F4','#8F7059','#EDD18C','#CA3F54','#01448B','#165dff',
          '#FFFF33','#B22222','#FFB6C1','#4B0082','#DDA0DD','#E6E6FA','#F08080','#483D8B','#40E0D0','#330033', 
          '#996666','#996699','#EE0000','#6666FF','#660099','#666699','#0000FF','#FF9933','#CC33CC','#003333',               
        ]; 
        res.data.forEach((item,index) => {
          let obj = {
            name: item.cargoType,
            value: item.rate,
            load: item.load,
            itemStyle: { 
              color: colorData[index]
            }
          };
          seriesData.push(obj);
        });
        pieChartData.value = seriesData;
        let pieChart = echarts.getInstanceByDom(document.getElementById("pieChart"));
        if(pieChart != null && pieChart != "" && pieChart != undefined){
          pieChart.dispose();
        }
        pieChart = echarts.init(document.getElementById('pieChart'));
        let option;
        option = {
          tooltip: {
            trigger: 'item',
            confine: true, //限制在图表区域内
            formatter: function (params) {
              return params.marker + params.data.name + ': ' + params.data.load + '吨，占比：' + params.data.value + '%'
            },    
          },
          legend: {   
            type: 'scroll',          
          },          
          series: [
            {
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: false,          
              },
              labelLine: {
                show: true, //标签连接线
              },  
              data: seriesData
            }
          ],          
        };
        option && pieChart.setOption(option);
      }
    });    
  };

  const year = ref(new Date().format("yyyy"));
  const currentDate = ref([new Date().format("yyyy")]);
  const columnsType = ['year'];
  const showYearPicker = ref(false);
  const confirmYear = (val) => {
    year.value = val.selectedValues[0];
    initStackedChart();
    showYearPicker.value = false;
  };
  //过闸船舶货物吨位统计
  const totalUpShipNum = ref(0);
  const totalDownShipNum = ref(0);
  const initStackedChart = () => {
    // let start = date.value.split('~')[0];
    // let end = date.value.split('~')[1];
    goodsTonAlys(
      "", 
      `${year.value}-01-01`, 
      `${year.value}-12-31`
    ).then((res) => {
      if(res.code === 200 && res.data){
        totalUpShipNum.value = res.data.totalUpShipNum;
        totalDownShipNum.value = res.data.totalDownShipNum;
        let emptyData = [];
        let num1Data = [];
        let num2Data = [];
        let num3Data = [];
        let num4Data = [];
        let upShipNumData = [];
        let downShipNumData = [];
        res.data.tons.forEach((item) => {
          emptyData.push(item.empty);
          num1Data.push(item.num1);
          num2Data.push(item.num2);
          num3Data.push(item.num3);
          num4Data.push(item.num4);
          upShipNumData.push(item.upShipNum);
          downShipNumData.push(item.downShipNum);
        });

        let stackedChart = echarts.getInstanceByDom(document.getElementById("stackedChart"));
        if(stackedChart != null && stackedChart != "" && stackedChart != undefined){
          stackedChart.dispose();
        }
        stackedChart = echarts.init(document.getElementById('stackedChart'));
        let option;
        option = {
          tooltip: {
            trigger: 'axis',
            confine: true, //限制在图表区域内 
            formatter: (params) => {
              // console.log(params)
              let template = `<b>${params[0].axisValue}</b><br>` + `上行船舶数<b style="float:right;padding-left: 20px;">${upShipNumData[parseInt(params[0].axisValue.split('月')[0])-1]}艘</b><br>下行船舶数<b style="float:right;padding-left: 20px;">${downShipNumData[parseInt(params[0].axisValue.split('月')[0])-1]}艘</b><br>`; 
              let count = 0;      
              for(let i = 0; i < params.length; i++){              
                let item = params[i];   
                template += item.marker + item.seriesName + `<b style="float:right;padding-left: 20px;">${item.value}艘</b><br>`;    
                count += item.value;                      
              }  
              return template + `<b style="position: absolute;top: 10px; right: 10px;">总共：${count}艘</b>`;
            },  
          },
          legend: {    
            type: 'scroll',         
          },
          grid: {
            top: '60px',
            left: '50px',
            right: '20px',
            bottom: '30px',
          },
          xAxis: [
            {
              type: 'category',
              axisLabel: {
                interval:0, 
              },
              data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '船舶数（艘）',
            }
          ],          
          series: [
            {
              name: '空载',
              type: 'bar', 
              stack: 'Search Engine',
              barWidth: "15%",
              // showBackground: true,
              emphasis: {
                //折线图的高亮状态。
                focus: 'series' 
              },
              data: emptyData,              
            },
            {
              name: '0-500吨',
              type: 'bar',
              stack: 'Search Engine',
              barWidth: "15%",
              // showBackground: true,
              emphasis: {
                focus: 'series'
              },
              data: num1Data
            },
            {
              name: '500-1000吨',
              type: 'bar',
              stack: 'Search Engine',
              barWidth: "15%",
              // showBackground: true,
              emphasis: {
                focus: 'series'
              },
              data: num2Data
            },
            {
              name: '1000-3000吨',
              type: 'bar',
              stack: 'Search Engine',
              barWidth: "15%",
              // showBackground: true,
              emphasis: {
                focus: 'series'
              },
              data: num3Data
            },
            {
              name: '3000吨以上',
              type: 'bar',
              stack: 'Search Engine',
              barWidth: "15%",
              // showBackground: true,
              emphasis: {
                focus: 'series'
              },
              data: num4Data
            }
          ]
        };

        option && stackedChart.setOption(option);
      }
    });    
  };

  //变形监测统计分析
  const deformationData = ref([]);
  const deformationAlysFunction = () => {
    defAlySmall().then((res) => {
      if(res.code === 200 && res.data.length){
        deformationData.value = res.data;
      }
    });
  };

  //变形监测观测周期统计分析
  const active1 = ref(0);
  const tabs = ref(null);
  const onClickTab1 = ({ title }) => {
    if(title == "船闸"){
      initBarChart1();
    }else if(title == "水坝"){
      initBarChart2();
    }
  };
  const chuanzhaxAxisData = ref([]);
  const chuanzhaseriesData = ref([]);
  const shuibaxAxisData = ref([]);
  const shuibaseriesData = ref([]);
  const circleAlysFunction = () => {
    circleAlys().then((res) => {
      if(res.code === 200){
        res.data.chuanzha.forEach((item) => {
          chuanzhaxAxisData.value.push(item.name);
          chuanzhaseriesData.value.push({
            value: item.cyc,
            itemStyle: {
              color: '#00C482'
            }
          })
        });
        res.data.shuiba.forEach((item) => {
          shuibaxAxisData.value.push(item.name);
          shuibaseriesData.value.push({
            value: item.cyc,
            itemStyle: {
              color: '#3177EC'
            }
          })
        });   
        initBarChart1();
        initBarChart2();           
      }
    });    
  };
  const initBarChart1 = () => {
    nextTick(() => {
      let barChart = echarts.getInstanceByDom(document.getElementById("barChart1"));
      if(barChart != null && barChart != "" && barChart != undefined){
        barChart.dispose();
      }
      barChart = echarts.init(document.getElementById('barChart1'));
      let option;
      option = {
        tooltip: {
          trigger: 'axis',
          confine: true, //限制在图表区域内
          formatter: function (params) {
            let template = `${params[0].axisValue}<br>`;         
            for(let i = 0; i < params.length; i++){
              let item = params[i];
              template += item.marker + ' ' + item.data.value + ' 次' + '<br>'
            }  
            return template  
          },  
        },
        legend: {},
        grid: {
          top: '18%',
          left: '45px',
          right: '20px',
          bottom: '20%',
        },
        dataZoom: [
          {
            show: false,
            type: "inside",
            // maxValueSpan: 8,
            // startValue: 0,
            // endValue: 6,
            zoomLock: false,
          },
        ],
        xAxis: {
          type: 'category',
          axisLabel: {
            rotate: 60,
          },
          data: chuanzhaxAxisData.value,
        },
        yAxis: {
          type: 'value',
          name: '统计次数',
        },
        series: [
          {
            type: 'bar',
            barWidth: "20%",
            showBackground: true,
            data: chuanzhaseriesData.value
          }
        ]
      };

      option && barChart.setOption(option);
    });  
  };
  const initBarChart2 = () => {
    nextTick(() => {
      let barChart = echarts.getInstanceByDom(document.getElementById("barChart2"));
      if(barChart != null && barChart != "" && barChart != undefined){
        barChart.dispose();
      }
      barChart = echarts.init(document.getElementById('barChart2'));
      let option;
      option = {
        tooltip: {
          trigger: 'axis',
          confine: true, //限制在图表区域内
          formatter: function (params) {
            let template = `${params[0].axisValue}<br>`;         
            for(let i = 0; i < params.length; i++){
              let item = params[i];
              template += item.marker + ' ' + item.data.value + ' 次' + '<br>'
            }  
            return template  
          },  
        },
        legend: {},
        grid: {
          top: '18%',
          left: '45px',
          right: '20px',
          bottom: '35%',
        },
        dataZoom: [
          {
            show: false,
            type: "inside",
            // maxValueSpan: 8,
            // startValue: 0,
            // endValue: 6,
            zoomLock: false,
          },
        ],
        xAxis: {
          type: 'category',
          axisLabel: {
            rotate: 60,
          },
          data: shuibaxAxisData.value,
        },
        yAxis: {
          type: 'value',
          name: '统计次数',
        },
        series: [
          {
            type: 'bar',
            barWidth: "20%",
            showBackground: true,
            data: shuibaseriesData.value
          }
        ]
      };

      option && barChart.setOption(option);
    });  
  };

  //实时水位
  const newWaterFunctin = () => {
    nextTick(() => {
      newWater().then((res) => {
        if(res.code === 200){
          let xAxisData = [];
          let seriesData = [];
          res.data.forEach((item) => {
            xAxisData.push(item.name);          
            seriesData.push(item.waterLevel);
          });
          let lineChart = echarts.getInstanceByDom(document.getElementById("lineChart"));
          if(lineChart != null && lineChart != "" && lineChart != undefined){
            lineChart.dispose();
          }
          lineChart = echarts.init(document.getElementById('lineChart'));
      
          let option;
          option = {
            tooltip: {
              trigger: 'axis',
              confine: true, //限制在图表区域内
              formatter: function (params) {
                let template = `${params[0].axisValue}<br>`;         
                for(let i = 0; i < params.length; i++){
                  let item = params[i];
                  template += item.marker + '水位值: ' + item.value + 'm' + '<br>'
                }  
                return template  
              },
            },
            grid: {
              top: '40px',
              left: '40px',
              right: '15px',
              bottom: '30%',
            },
            dataZoom: [
              {
                show: false,
                type: "inside",
                // maxValueSpan: 8,
                // startValue: 0,
                // endValue: 6,
                zoomLock: false,
              },
            ],
            xAxis: {
              type: 'category',
              axisLabel: {
                rotate: 60,
              },              
              data: xAxisData,
              // name: '时间',
              // nameTextStyle: {
              //   fontWeight: "500",
              //   fontSize: "10px",
              //   color: "rgba(0,0,0,0.45)",
              // },
            },
            yAxis: {
              type: 'value',
              name: '水位（m）',
            },
            series: [
              {
                data: seriesData,
                type: 'line',
                
              }
            ]
          };
          option && lineChart.setOption(option);
        }
      });  
    });
  };

  onMounted(() => {
    date.value = new Date().format('yyyy-MM-dd') + '~' + new Date().format('yyyy-MM-dd');
    // getShipLockFunction();
    initPieChart();
    initStackedChart();
    newWaterFunctin();
    // deformationAlysFunction();
    // circleAlysFunction();
  });
</script>

<style lang="scss" scoped>
  .container{
    margin: 0 16px;
    padding-bottom: 16px;
    .filter{
      display: flex;
      margin: 20px 0px 16px 0px;
    }
    .content{
      background: #FFFFFF;
      box-shadow: 0px 4px 8px 2px rgba(0,0,0,0.08);
      border-radius: 8px;
      margin-bottom: 16px;
      .title{
        font-size: 16px;
        font-weight: bold;
        color: rgba(0,0,0,0.85);
        // text-align: center;
        padding: 8px 0px 8px 16px;
        background: rgba(22,93,255,0.05);
        box-shadow: 0px 1px 0px 0px rgba(0,0,0,0.1);
      }
      .explain{
        font-size: 12px;
        color: #595959;
        margin: 8px 16px;
        padding: 8px;
        background: #F8F9FB;
      }
      .count{
        display: flex;
        justify-content: space-around;
        margin-top: 8px;
        .item{
          display: flex;
          align-items: center;
          .name{
            font-size: 12px;
            font-weight: 500;
            color: rgba(0,0,0,0.85);
          }
          .value{
            font-size: 18px;
            font-weight: bold;
            color: #3177EC;
            padding-left: 12px;
          }
        }
      }
      .list{
        height: 270px;
        overflow-y: scroll;
        padding: 16px 0;
        .list-item{
          margin: 0 32px;
          border-bottom: 1px solid #F0F0F0;
          .item-title{
            font-size: 14px;
            font-weight: bold;
            color: rgba(0,0,0,0.9);
          }
          .item-name{
            display: flex;
            div{
              width: 25%;
              // text-align: center;              
              // background: rgba(49,119,236,0.1);
              padding: 2px 0;
              font-weight: 400;
              font-size: 12px;
              color: #595959;
            }
          }
          .item-value{
            display: flex;
            margin: 4px 0;
            div{
              width: 25%;
              // text-align: center;
              font-weight: bold;
              font-size: 21px;
              color: #262626;
            }
          }
        }
      }   
      .pie-table {
        margin: 0 16px;
        .pie-tbody {
          font-size: 14px;
          font-weight: 500;
          color: #595959;
          .pie-tr {
            display: flex;
            align-items: center;
            justify-content: space-around;
            .li{
              width: 8px;
              height: 8px;
              border-radius: 0px 0px 0px 0px;
              opacity: 1;
              border-radius: 50%;
              margin-right: 6px;
            }
            // .pie-td:first-of-type {
            //   margin-left: 20px;
            // }
            // .pie-td:last-of-type {
            //   margin-right: 20px;
            // }
          }
        }
      }   
    }
    :deep(.van-cell){
      padding: 4px 8px;
    }
  }
</style>